<template>
  <div :id="$props.name" class="editor-container" />
</template>

<script>
import Quill from 'quill'
import request from '@/utils/request'
export default {
  name: 'MyForm',
  props: {
    data: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: 'editor'
    }
  },
  data() {
    return {
      quill: null
    }
  },
  watch: {
    data: {
      handler(val) {
        if (!this.quill) {
          setTimeout(() => {
            this.quill.clipboard.dangerouslyPasteHTML(val)
            // this.quill.setSelection(val.length, val.length)
          }, 200)
        } else {
          this.quill.clipboard.dangerouslyPasteHTML(val)
          // this.quill.setSelection(val.length, val.length)
        }
      }
    }
  },
  mounted() {
    const quill = new Quill(`#${this.$props.name}`, {
      theme: 'snow',
      placeholder: '请输入内容'
    })
    this.quill = quill
    const timer = true
    quill.on('text-change', async(delta, oldDelta, source) => {
      this.$emit('onChange', quill.root.innerHTML)
      // const value = quill.root.innerHTML
      // this.replaceImage(value)

      return
      const { insert } = delta.ops[delta.ops.length - 1]

      return
      if (insert && insert instanceof Object && insert.image) {
        // console.log(delta, value)
        return
        const { url } = await this.upload(insert.image)
        console.log(url, '--', value)

        const newImageTag = 'new-image'
        const newValue = value.replace(`<img src="${url}"`, `<img class="${newImageTag}" src="${url}"`)
        console.log(newValue, '--new')

        // 只替换带有 'new-image' 标识的图片URL
        const reg = new RegExp(`<img class="${newImageTag}" [^>]*src=['"]([^'"]+)[^>]*>`, 'gi')
        const finalValue = url ? newValue.replace(reg, `<img src="${url}"`) : newValue

        // 移除 'new-image' 标识
        const removeTagReg = new RegExp(`<img class="${newImageTag}" [^>]*src=['"]([^'"]+)[^>]*>`, 'gi')
        const finalValueWithoutTag = finalValue.replace(removeTagReg, '<img src="$1"')

        console.log(finalValueWithoutTag, '-000')
      }

      if (timer) {
        // timer = false

        // setTimeout(() => {
        //   timer = true
        // }, 1000)
      }
    })
  },
  methods: {
    replaceImage(html) {
      const base64Regex = /<img[^>]+src="(data:image\/[^;]+;base64[^"]+)"[^>]*>/g
      const matches = [...html.matchAll(base64Regex)]
      console.log(matches)

      for (const match of matches) {
        const fullImgTag = match[0] // 完整 <img> 标签
        const base64Data = match[1] // 捕获的 Base64 数据

        try {
          // 上传到 OSS 并获取 URL
          const remoteUrl = this.upload(base64Data)

          // 替换 src 属性
          // processedHtml = processedHtml.replace(
          //   fullImgTag,
          //   fullImgTag.replace(base64Data, remoteUrl)
          // );
        } catch (error) {
          console.error('上传失败:', error)
          // 可选：保留原 Base64 或标记错误
        }
      }
    },
    async upload(val) {
      try {
        const data = await request({ url: 'client/upload/base64Upload', method: 'post', data: { imgData: val }})
        return Promise.resolve({ url: data.data, type: 'success' })
      } catch (error) {

      }
    }
  }

}
</script>
<style lang="scss">

.editor-container {
  height: 300px;
}
</style>
